package com.artron.mediaartron.ui.fragment.center;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.artron.baselib.adapter.recyclerview.BaseViewHolder;
import com.artron.baselib.adapter.recyclerview.CommonAdapter;
import com.artron.baselib.adapter.recyclerview.DividerItemDecoration;
import com.artron.baselib.adapter.recyclerview.LoadMoreWrapper;
import com.artron.baselib.adapter.recyclerview.MultiItemTypeAdapter;
import com.artron.baselib.base.BaseLoadingFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.ToastUtil;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.WorksData;
import com.artron.mediaartron.data.entity.WorksData.WorksListBean;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.net.api.HostApi;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.adapter.LoadMoreListener;
import com.artron.mediaartron.ui.fragment.center.WorksFinishFragment.ContentType;
import com.artron.mediaartron.ui.fragment.dialog.NormalDialogFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;

import static com.artron.mediaartron.data.production.FrameConstant.BLANK_CUSTOM_MADE;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-11-13.
 */

public class WorksFinishContentFragment extends BaseLoadingFragment<WorksData> {

    @BindView(R.id.WorksFinishContentFragment_recycler)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.WorksFinishContentFragment_refresh)
    protected SmartRefreshLayout mRefreshLayout;
    private ContentType mType;
    private List<WorksListBean> mFragmentData;
    private ClassicsHeader mRefreshHeader;
    private LoadMoreWrapper mWrapper;

    public static WorksFinishContentFragment newInstance(ContentType type) {
        WorksFinishContentFragment fragment = new WorksFinishContentFragment();
        fragment.init(type);
        return fragment;
    }

    private void init(ContentType type) {
        this.mType = type;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_works_finish_content;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (TextUtils.isEmpty(mType.getType())) {
            show();
        }
    }

    @Override
    protected void initVariable() {
        mRefreshHeader = new ClassicsHeader(mContext);
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL_LIST, R.drawable.shape_gray_f4f5f5_10dp));
    }

    @Override
    public void initViewWithData(WorksData data) {
        mFragmentData = data.getWorksList();

        mRefreshLayout.finishRefresh();


        final CommonAdapter adapter = new CommonAdapter<WorksListBean>(mContext,
                R.layout.item_works_finish_content, data.getWorksList()) {

            private int mMeasuredHeight;

            private void resizeImageView(BaseViewHolder holder, WorksListBean bean) {
                FrameLayout frameLayout = holder.getView(R.id.ItemWorksFinishContent_fl_frame);
                if (frameLayout != null && mMeasuredHeight == 0) {
                    int height = frameLayout.getLayoutParams().height;
                    int spec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
                    frameLayout.measure(spec, spec);
                    mMeasuredHeight = frameLayout.getMeasuredHeight();
                }

                ImageView imageView = holder.getView(R.id.ItemWorksFinishContent_iv_image);
                String[] sizeArr = bean.getSize().split("X");
                float width = Float.parseFloat(sizeArr[0]);
                float height = Float.parseFloat(sizeArr[1]);

                float per = mMeasuredHeight / Math.max(width, height);
                float layoutWidth = (width - BLANK_CUSTOM_MADE) * per;
                float layoutHeight = (height - BLANK_CUSTOM_MADE) * per;
                ViewGroup.LayoutParams params = imageView.getLayoutParams();
                params.height = (int) layoutHeight;
                params.width = (int) layoutWidth;
                imageView.setLayoutParams(params);
            }

            @Override
            protected void convert(BaseViewHolder holder, WorksListBean bean, int position) {
                String typeCode = bean.getTypeCode();
                for (ContentType contentType : ContentType.values()) {
                    if (contentType.getType().equals(typeCode)) {
                        holder.setText(R.id.ItemWorksFinishContent_tv_frame_type, contentType.name());
                    }
                }
                resizeImageView(holder, bean);

                holder.setText(R.id.ItemWorksFinishContent_tv_create_date, "创建时间：" + bean.getCreateTime())
                        .setText(R.id.ItemWorksFinishContent_tv_frame_name, bean.getName())
                        .setText(R.id.ItemWorksFinishContent_tv_frame_shape,
                                "外观尺寸".equals(bean.getShape()) ? "" : bean.getShape())
                        .setText(R.id.ItemWorksFinishContent_tv_frame_size, bean.getSize() + "mm")
                        .setImageUrl(R.id.ItemWorksFinishContent_iv_image, bean.getThumbnailPath());
            }

            @Override
            protected void onViewHolderCreate(final BaseViewHolder holder) {
                holder.setOnClickListener(R.id.ItemWorksFinishContent_btn_delete, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        NormalDialogFragment fragment = NormalDialogFragment.newInstance(
                                "确定删除这个作品吗？", "取消", "确定");
                        fragment.show(getChildFragmentManager(), fragment.getOurTag());
                        fragment.setOnNegativeClickListener(new Action0() {
                            @Override
                            public void call() {
                                final int position = holder.getAdapterPosition();
                                WorksListBean bean = mDatas.get(position);

                                String passId = AppProfile.getUserInfo().getPassId();
                                RetrofitHelper.subscript(RetrofitHelper.getWorksApi().deleteWorks(passId,
                                        bean.getId()), new Action1<Response>() {
                                    @Override
                                    public void call(Response response) {
                                        if (response != null) {
                                            if ("1".equals(response.getStatus())) {
                                                mFragmentData.remove(position);
                                                mDatas.remove(position);
                                                mWrapper.notifyItemRemoved(position);
                                                ToastUtil.show("删除成功");
                                            } else {
                                                ToastUtil.show(response.getMessage());
                                            }
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
                holder.setOnClickListener(R.id.ItemWorksFinishContent_btn_buy_again, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HostApi api = RetrofitHelper.getHostApi();
                        String passId = AppProfile.getUserInfo().getPassId();
                        int position = holder.getAdapterPosition();
                        WorksListBean bean = mFragmentData.get(position);
                        RetrofitHelper.subscript(api.saveTrolleyDetail(passId, bean.getId(), 1, bean.getSkuCode(),
                                "artron", "android"), new Action1<Response>() {
                            @Override
                            public void call(Response response) {
                                ToastUtil.show(response.getMessage());
                            }
                        });
                    }
                });
            }
        };
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.SimpleOnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                WorksListBean bean = mFragmentData.get(position);
                GeneralActivity.start(mContext, GeneralActivity.MY_WORKS_DETAIL, "已完成", bean);
            }
        });

        mWrapper = new LoadMoreWrapper(adapter);
        mWrapper.setLoadMoreView(R.layout.layout_loading_more);
        mWrapper.setOnLoadMoreListener(new LoadMoreListener<>(mFragmentData, mWrapper, new Func1<Integer, Observable<Response<WorksData>>>() {
            @Override
            public Observable<Response<WorksData>> call(Integer integer) {
                String passId = AppProfile.getUserInfo().getPassId();
                return RetrofitHelper.getWorksApi().queryWorkses(passId, integer + "", "10", "-1",
                        mType.getType());
            }
        }));
        mRecyclerView.setAdapter(mWrapper);


        mRefreshLayout.setRefreshHeader(mRefreshHeader);
        mRefreshLayout.setOnRefreshListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                showImmediate();
            }
        });
    }

    @Override
    protected Observable<Response<WorksData>> retrofitData() {
        String passId = AppProfile.getUserInfo().getPassId();
        return RetrofitHelper.getWorksApi().queryWorkses(passId, "1", "10", "-1", mType.getType());
    }

    @Override
    protected int getErrorViewId() {
        return R.layout.general_empty;
    }
}
